<template>
    <div class="staff-container">
        <!-- 顶部操作栏 -->
        <div class="top-bar">
            <h2>员工管理</h2>
            <el-button type="primary" @click="showAddModal">新增员工</el-button>
        </div>

        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline class="mb-4">
            <el-form-item label="姓名">
                <el-input v-model="searchForm.name" placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="员工编号">
                <el-input v-model="searchForm.employeeId" placeholder="请输入员工编号" />
            </el-form-item>
            <el-form-item label="职位">
                <el-input v-model="searchForm.position" placeholder="请输入职位" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchStaff">搜索</el-button>
                <el-button @click="resetsetSearch">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 员工表格 -->
        <el-table :data="staffList" border stripe>
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column label="员工编号" prop="employeeId" />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="职位" prop="position" />
            <el-table-column label="联系电话" prop="phone" />
            <el-table-column label="入职日期" prop="hireDate">
                <template #default="scope">
                    {{ formatDate(scope.row.hireDate) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="text" @click="showEditModal(scope.row)">编辑</el-button>
                    <el-button type="text" danger @click="deleteStaff(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '新增员工' : '编辑员工'"
            width="600px"
        >
            <el-form
                ref="staffForm"
                :model="staffForm"
                :rules="staffRules"
                label-width="120px"
            >
                <el-form-item label="员工编号" prop="employeeId">
                    <el-input v-model="staffForm.employeeId" placeholder="请输入员工编号" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="staffForm.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="职位" prop="position">
                    <el-input v-model="staffForm.position" placeholder="请输入职位" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="staffForm.phone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="入职日期" prop="hireDate">
                    <el-date-picker
                        v-model="staffForm.hireDate"
                        type="date"
                        placeholder="选择入职日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveStaff">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
module.exports = {
    data() {
        return {
            staffList: [],
            searchForm: { name: '', employeeId: '', position: '' },
            dialogVisible: false,
            dialogType: 'add',
            staffForm: {
                id: null,
                employeeId: '',
                name: '',
                position: '',
                phone: '',
                hireDate: ''
            },
            staffRules: {
                employeeId: [{ required: true, message: '请输入员工编号', trigger: 'blur' }],
                name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
                ],
                hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }]
            }
        };
    },
    mounted() {
        this.getStaffList();
    },
    methods: {
        // 获取员工列表
        async getStaffList() {
            try {
                const res = await this.$axios.get('/staff');
                this.staffList = res.data;
            } catch (error) {
                this.$message.error('获取员工列表失败：' + error.message);
            }
        },

        // 搜索员工
        async searchStaff() {
            try {
                const res = await this.$axios.get('/staff/search', { params: this.searchForm });
                this.staffList = res.data;
            } catch (error) {
                this.$message.error('搜索员工失败：' + error.message);
            }
        },

        // 重置搜索
        resetSearch() {
            this.searchForm = { name: '', employeeId: '', position: '' };
            this.getStaffList();
        },

        // 显示新增弹窗
        showAddModal() {
            this.dialogType = 'add';
            this.staffForm = {
                id: null,
                employeeId: '',
                name: '',
                position: '',
                phone: '',
                hireDate: ''
            };
            this.dialogVisible = true;
        },

        // 显示编辑弹窗
        showEditModal(row) {
            this.dialogType = 'edit';
            // 深拷贝对象，避免直接修改表格数据
            this.staffForm = JSON.parse(JSON.stringify(row));
            // 格式化日期显示
            if (this.staffForm.hireDate) {
                this.staffForm.hireDate = this.formatDateForInput(this.staffForm.hireDate);
            }
            this.dialogVisible = true;
        },

        // 保存员工信息
        async saveStaff() {
            const valid = await this.$refs.staffForm.validate();
            if (!valid) return;

            try {
                if (this.dialogType === 'add') {
                    await this.$axios.post('/staff', this.staffForm);
                    this.$message.success('员工新增成功');
                } else {
                    await this.$axios.put(`/staff/${this.staffForm.id}`, this.staffForm);
                    this.$message.success('员工信息更新成功');
                }
                this.dialogVisible = false;
                this.getStaffList();
            } catch (error) {
                this.$message.error('操作失败：' + (error.response?.data?.message || error.message));
            }
        },

        // 删除员工
        async deleteStaff(id) {
            try {
                await this.$confirm('确定要删除该员工信息吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                await this.$axios.delete(`/staff/${id}`);
                this.$message.success('员工信息删除成功');
                this.getStaffList();
            } catch (error) {
                // 取消删除不做处理
            }
        },

        // 格式化日期显示
        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        },

        // 格式化日期用于输入框
        formatDateForInput(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toISOString().split('T')[0];
        }
    }
};
</script>

<style scoped>
.staff-container {
    padding: 20px;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

/* 表格行悬停效果增强 */
::v-deep .el-table__row:hover {
    background-color: #f0f7ff;
}

/* 按钮样式优化 */
::v-deep .el-button--text {
    margin-right: 10px;
}
</style>
